import React, { createContext, useState, useEffect, memo } from 'react';
import HeadTop from '@/components/HeadTop';
import { List } from 'react-vant'
import "./index.less"
import ApiIndex from '@/api/notice';

const ListItem = memo(({ el }) => {
    return (
        <div className="n-line" key={el.id}>
            <div className="n-img">
                <img src={require('../../../assets/img/horn_icon.png').default} alt="" />
            </div>
            <div className="n-info">
                <div className="i-tit">
                    <div className="i-name">{el.title}</div>
                    <div className="i-time">{el.createTime}</div>
                </div>
                <div className="i-txt">
                    {el.content}
                </div>
            </div>
        </div>
    )
})

function Index({ history }) {
    const [list, setList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [finished, setFinished] = useState(false);
    const [pageIndex, setPageIndex] = useState(1);

    useEffect(() => {
        getList()
    }, []);

    const getList = async () => {
        setLoading(true);
        let params = {
            page: pageIndex,
            size: 4,
        }
        try {
            let res = await ApiIndex.notice(params)
            if (res.data.code == 0) {
                let _data = res.data.data.records
                setList((prevList) => [...prevList, ..._data]);
                // 判断是否还有更多数据
                if (_data.length < 4) {
                    setFinished(true);
                } else {
                    setPageIndex((prevIndex) => prevIndex + 1);
                }
                setLoading(false);
            }
        } catch (error) {
            console.error('Error:', error);
            setLoading(false);
        }
    }

    const loadMoreData = () => {
        setPageIndex((prevIndex) => prevIndex + 1);
        // fetchData();
    };

    return (
        <div className='page-wrapper'>
            <HeadTop
                title="消息"
                history={history}
            ></HeadTop>
            <div className="page-body" style={{ padding: 15 }}>
                <List finished={finished} errorText='请求失败，点击重新加载' onLoad={getList}>
                    {
                        list.map(el => <ListItem
                            key={el.id}
                            item={el}
                        ></ListItem>)
                    }
                    {loading ? <div className='loadingTxt'>Loading...</div> : finished ? <div className='loadingTxt'>无更多数据</div> : null}
                </List>
                {!loading && !finished && (
                    <div style={{ textAlign: 'center', padding: '10px', marginBottom: '10px' }}>
                        <span onClick={loadMoreData}>Load More</span>
                    </div>
                )}
            </div>
        </div>
    );
}

export default Index;
